const url = import.meta.env.VITE_API_URL;
export const myRequest = (options) => {
  return new Promise(async (resolve, reject) => {
    uni.showLoading({
      title: "加载中...",
    });
    await uni.request({
      url: url + options.url,
      method: options.method || "POST", // 默认POST请求
      data: options.data || {},
      header: {
        Accept: "application/json, text/plain, */*",
        Authorization: "Bearer " + uni.getStorageSync("token"),
      },
      fail: (err) => {
        uni.hideLoading();
        // 全局提示错误，无需业务代码再处理
        uni.showToast({ title: "请求失败，请重试", icon: "none" });
        reject(err); // 仍然抛出错误，供特殊场景捕获
      },
      success: (res) => {
        // console.log("请求成功:", res);
        // uni.hideLoading();
        // 登录失效处理
        if (res.data.code == 20001) {
          uni.clearStorage();
          uni.showToast({ title: "请求失败，请重试", icon: "none" });
          // uni.showToast({
          //   title: "请预先登录",
          //   duration: 2500,
          //   icon: "none", // 建议用none，避免success图标误导
          // });
          setTimeout(() => {
            uni.reLaunch({ url: "/pages/user/index" });
          }, 2600);
          return; // 终止后续逻辑
        }
        uni.hideLoading();
        resolve(res.data); // 直接返回data，简化调用
      },
      complete: (e) => {
        uni.hideLoading();
        if (e.data.code != 10000) {
          // console.log(e.data);
          uni.showToast({ title: e.data.message, icon: "none" });
        }
        // uni.hideLoading();
        // console.log(e);
      },
      fail: (err) => {
        uni.hideLoading();
        uni.showToast({
          title: "请求接口失败",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};
